package de.tum.in.eist.im.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import de.tum.in.eist.im.client.domain.User;

/**
 * @author Christian Ittner
 */
public class LoginDialog extends DialogBox {
	ChatServiceAsync chatService;
	AsyncCallback<Void> callback;
	Grid grid = new Grid(3, 2);	
    TextBox usernameBox = new TextBox();
    PasswordTextBox passwordBox = new PasswordTextBox();	
    Button submitButton = new Button(
        "Login!", new ClickHandler() {
            public void onClick(ClickEvent event) {  
            	chatService.login(new User(usernameBox.getText(), passwordBox.getText()), chatServiceLoginCallback);
            }
        }
    );
    
    AsyncCallback<Boolean> chatServiceLoginCallback = new AsyncCallback<Boolean>() {
        public void onSuccess(Boolean result) {
            if(result) {
          	    //login successful
          	    callback.onSuccess(null);
          	    hide();

            } else {
          	    // login fehlgeschlagen: als neuen account registrieren und erneut versuchen.
          	    chatService.registerNewUser(new User(usernameBox.getText(), passwordBox.getText()), new AsyncCallback<Void>() {
					public void onFailure(Throwable exception) {
						//verbindung mit server gescheitert.
						callback.onFailure(null);
					}
					public void onSuccess(Void arg0) {
						//->registrierung erfolgreich, also: einloggen.
						chatService.login(new User(usernameBox.getText(), passwordBox.getText()), chatServiceLoginCallback);
					}
				});
            }
        }
        public void onFailure(Throwable exception) { 
			//verbindung mit server gescheitert.
			callback.onFailure(null);
        }
    };
    
	public LoginDialog(ChatServiceAsync chatService) {
		this.chatService=chatService;	
    	setText("Login");
      	setAnimationEnabled(true);
      	setGlassEnabled(true);
  		center();

        grid.setWidget(0, 0, new Label("Username:"));
        grid.setWidget(0, 1, new TextBox());
        grid.setWidget(1, 0, new Label("Password:"));
        grid.setWidget(1, 1, new PasswordTextBox());
        grid.setWidget(2, 1, submitButton);
        setWidget(grid);
    }

	public void show(AsyncCallback<Void> asyncCallback) {
		callback = asyncCallback;
		show();
	}
    
    
    
}